package com.cswnode.Controller;

import com.cswnode.Annotations.LoginJudgment;
import com.cswnode.Entity.Comment;
import com.cswnode.Entity.DiscussPost;
import com.cswnode.Entity.Event;
import com.cswnode.Event.EventProducer;
import com.cswnode.Service.CommentService;
import com.cswnode.Service.DiscussPostService;
import com.cswnode.Util.Constant;
import com.cswnode.Util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

/**
 * @author csw
 * @create 2020/9/25 10:25
 */
@Controller
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private DiscussPostService discussPostService;

    //用户私信功能
    @LoginJudgment
    @PostMapping("/add/{discussPostId}")
    public String addComment(@PathVariable("discussPostId")int discussPostId, Comment comment){
        if (comment.getTargetId() == null){
            comment.setTargetId(0);
        }
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        commentService.insertComment(comment);
        //触发评论事件
        Event event = new Event()
                .setTopic(Constant.TOPIC_COMMENT)
                .setUserId(hostHolder.getUser().getId())
                .setEntityId(comment.getEntityId())
                .setEntityType(comment.getEntityType())
                .setData("postId",discussPostId);
        if (event.getEntityType() == Constant.ENTITY_TYPE_POST){
            DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(target.getId());
        }else if (event.getEntityType() == Constant.ENTITY_TYPE_COMMENT){
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        eventProducer.fireEvent(event);

        return "redirect:/findDiscussPost/"+ discussPostId;

    }
}
